<?php

namespace app\api\controller\port;

use app\common\controller\Api;

use think\Exception;
use app\common\model\Order as OrderModel;
use app\common\model\MoneyLog;

/**
 * 司机接口
 * 
 */
class Driver extends Api
{

    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];
    
    protected $model = null;
    protected $driver = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new OrderModel();
        $ident = $this->auth->ident;
        $ident == 1 && $this->error('您不是司机');
        $driver = db('driver')->where('user_id',$this->auth->id)->find();
        empty($driver) && $this->error('没有找到司机信息');
        $this->driver = $driver;
    }


    /**
     * 获取司机信息
     * 
     */
    public function getDriverInfo()
    {
        $info = $this->driver;
        $info['avatar_image'] = cdnurl($info['avatar_image'],true);
        $info['money'] = $this->auth->money;
        $this->success('Success',$info);
    }

    /**
     * 顶部统计
     * 
     */
    public function statistics()
    {
        $uid = $this->auth->id;
        $Model = $this->model;
        $where = [
            'driver_id'=>$this->driver['id'],
            'status' => 3
        ];
        $all_num = $Model->where($where)->count();
        $all_money = db('user_money_log')->where(['user_id'=>$uid,'money'=>['>',0]])->sum('money');
        
        // $begin = strtotime(date('Y-m-d'));
        // $end = $begin + 86400;
        // $where['depart_time'] = [['>=',$begin],['<',$end]];
        $today_num = $Model->where($where)->whereTime('depart_time','d')->count();
        $today_money = db('user_money_log')->where(['user_id'=>$uid,'money'=>['>',0]])->whereTime('createtime','d')->sum('money');

        $this->success('Success',compact('today_num','today_money','all_num','all_money'));
    }


    /**
     * 司机订单
     * 
     */
    public function driverList()
    {
        $status = I('post.status',1);
        $limit = I('post.limit',10);

        $where = ['driver_id'=>$this->driver['id']];
        switch ($status) {
            case 0: //全部
                
                break;
            case 1: //进行中
                $where['status'] = ['in',[1,2]];
                break;
            case 2: //已完成
                $where['status'] = 3;
                break;
            case 3: //退款
                $where['status'] = ['in',[4,5,6]];
                break;
        }

        $Model = $this->model;
        $Model->where = $where;
        $Model->limit = $limit;
        $Model->fields = 'id,type,status,depart_time,start_station,start_station_coordinate,end_station,pay_price,passenger_ids,mobile,up_car_data,down_car_data,order_desc';
        $list = $Model->_list();
        
        $refund_rate = config('site.refund_rate');
        foreach($list['data'] as &$val){
            $passenger_ids_arr = explode(',',$val['passenger_ids']);
            $val['passenger_num'] = count($passenger_ids_arr);
            $val['depart_time'] = date('Y-m-d H:i',$val['depart_time']);
            
            $val['up_car_data'] = json_decode($val['up_car_data']);
            $val['down_car_data'] = json_decode($val['down_car_data']);
            
            $val['refund_rate'] = $refund_rate;
            $order_pay_price = $val['pay_price'];
            $val['rate_money'] = round($order_pay_price * $refund_rate / 100, 2);
        }
        $this->success('Success',$list);
    }


    /**
     * 订单详情
     * 
     */
    public function orderDetail()
    {
        $order_id = I('post.order_id');
        empty($order_id) && $this->error('订单参数有误');

        $detail = $this->getOrderDetail(['id'=>$order_id,'driver_id'=>$this->driver['id']]);
        empty($detail) && $this->error('没有找到订单信息');
        $detail->up_car_data = json_decode($detail->up_car_data);
        $detail->down_car_data = json_decode($detail->down_car_data);
        //退款信息
        $refund_data = [];
        if(in_array($detail->status,[4,5,6])){
            $refund_data = db('order_refund')
            ->where('order_id',$detail->id)
            ->field('refund_desc,refund_rate,rate_money,refund_money,create_time')
            ->find();
        }
        $detail->refund_data = $refund_data;
        // 乘客信息
        $passenger = [];
        if($detail->type == 1){
            $passenger = db('passenger')->where('id','in',$detail->passenger_ids)->field('id,name,mobile,idcard')->select();
        }
        $detail->passenger_data = $passenger;
        //退款费率信息
        $refund_rate = config('site.refund_rate');
        $order_pay_price = $detail->pay_price;
        $rate_money = round($order_pay_price * $refund_rate / 100, 2);
        $detail->refund_rate_data = compact('refund_rate','rate_money');

        $this->success('Success',$detail);
    }


    /**
     * 确认送达
     * 
     */
    public function sureOrder()
    {
        $order_id = I('post.order_id');
        empty($order_id) && $this->error('订单参数有误');

        $detail = $this->getOrderDetail(['id'=>$order_id,'driver_id'=>$this->driver['id']]);
        empty($detail) && $this->error('没有找到订单信息');
        $detail['status'] == 2 || $this->error('当前订单不可送达');

        $uid = $this->auth->id;
        try{
            db()->startTrans();

            $detail->save(['status'=>3]);
    
            $driver_rate = config('site.driver_rate');
            $pay_price = $detail->pay_price;
            $rate_money = round($pay_price * $driver_rate / 100, 2);
            $driver_money = round($pay_price - $rate_money, 2);

            $user_money = $this->auth->money;
            db('user')->where('id',$uid)->setInc('money',$driver_money);

            MoneyLog::create([
                'user_id' => $uid,
                'money' => $driver_money, 
                'before' => $user_money, 
                'after' => $user_money + $driver_money, 
                'memo' => "乘客乘车增加余额",
                'order_id' => $order_id,
                'order_sn' => $detail->order_sn,
                'driver_rate' => $driver_rate,
                'rate_money' => $rate_money,
            ]);
            
            db()->commit();
            $this->success('已确认送达');
        }catch (Exception $e){
            db()->rollback();
            $this->error($e->getMessage()?:'操作失败');
        }
        
    }


    /**
     * 核销订单
     * 
     */
    public function checkOrder()
    {
        $order_sn = I('post.order_sn');
        $detail = $this->getOrderDetail(['order_sn'=>$order_sn,'driver_id'=>$this->driver['id']]);
        empty($detail) && $this->error('没有找到车票信息');
        $detail['status'] == 1 || $this->error('当前车票不可核销乘坐');

        $ret = $this->model->where(['order_sn'=>$order_sn,'driver_id'=>$this->driver['id']])->update(['status'=>2]);
        $ret && $this->success('已核销');
        $this->error('核销失败');
    }


    /**
     * 司机余额记录
     * 
     */
    public function moneyLog()
    {
        $uid = $this->auth->id;
        $limit = I('post.limit',10);

        $money_log = db('user_money_log')
            ->where('user_id',$uid)
            ->order('createtime desc')
            ->paginate($limit)
            ->each(function($val){
                $val['createtime'] = date('Y-m-d H:i:s',$val['createtime']);
                return $val;
            });

        $this->success('Success',$money_log);
    }

    private function getOrderDetail($where)
    {
        $Model = $this->model;
        $Model->where = $where;
        $Model->limit = 1;
        return $Model->_list();
    }



}
